package com.ymx.darling.datasource.routing.dialect;

import com.ymx.darling.datasource.routing.DataSourceHolder;
import com.ymx.darling.dialect.Dialect;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 数据源方言代理实例 用于多数据源下不同数据库的切换
 * @author 爱Java的小于
 */
public class DialectProxy implements InvocationHandler {
    private final Map<String, Dialect> dialectMap;
    private final String master;

    public DialectProxy(Map<String, Dialect> dialectMap, String master) {
        this.dialectMap = dialectMap;
        this.master = master;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String currentDataSource = DataSourceHolder.getCurrent();
        if (currentDataSource == null) {
            currentDataSource = master;
        }
        Dialect dialect = dialectMap.get(currentDataSource);
        return method.invoke(dialect, args);
    }
}
